<?php
  //error_reporting(E_ALL);
  session_start();

  date_default_timezone_set('Asia/Kolkata');

  $username = 'root';
  $password = '';
  $host = 'localhost';
  $dbName = 'mb125';

  /* DB Connection*/
  $link = mysql_connect($host,$username,$password) or die("Unable to connect MYSQL ".mysql_error());

  /* Database selection */
  mysql_select_db($dbName, $link)or die("Unable to select DB ".mysql_error());


  /*
   * Replacement of print_r()
   * */
  function pr($data)
  {
    //return false;
    echo '<pre style="font-size:20px;color:#FFF;background-color:#000;">';
    print_r($data);
    echo '</pre>  ';
  }

  /**
   * INSERT VALUES IN DB TABLE
   * @param $table_name STRING "name of db table"
   * @param $data ARRAY "ARRAY of Values to be inserted"
   * @return INT last insert id
   * USAGE : insert('users',$_POST);
   * */
  function insert($table_name='', $data=array())
  {
    $query = "INSERT INTO `$table_name` SET";

    foreach ($data as $colName=>$value)
    {
      $query .= "`$colName`= '$value',";
    }
    $query = rtrim($query, ' ,');
    pr($query);

    mysql_query($query) or die(mysql_error());

    return mysql_insert_id();
  }

  /**
   * UPDATE VALUES IN DB TABLE
   * @param $table_name STRING "name of db table"
   * @param $data ARRAY "ARRAY of Values to be inserted"
   * @param $where STRING Ex:=> "WHERE `id`='23'"
   * @return INT Updated Rows
   * USAGE : update('users',$_POST,WHERE `id`='23');
   * */
  function update($table_name='', $data=array(), $where)
  {
    $query = "UPDATE `$table_name` SET";

    foreach ($data as $colName=>$value)
    {
      $query .= "`$colName`= '$value',";
    }
    $query = rtrim($query, ' ,');

    $query .= " $where";

    pr($query);

    mysql_query($query) or die(mysql_error());

    return mysql_affected_rows();
  }



  /**
   * SELECT VALUES FROM DB TABLE
   * @param $table_name STRING "name of db table"
   * @param $where STRING Ex:=> "WHERE `id`='23'"
   * @return RESOURCE
   * USAGE : fetchAll('users',"WHERE `id`='23'");
   * */
  function fetchAll($table_name='', $where='',$limit='',$order='')
  {

    $query = "SELECT * FROM `$table_name` $where $order $limit";
    pr($query);
    $result = mysql_query($query) or die(mysql_error());
    return $result;
  }

  /**
   * COUNT TOTAL RECORDS IN DB TABLE
   * @param $table_name STRING "name of db table"
   * @param $where STRING Ex:=> "WHERE `id`='23'"
   * @return INT Total Records
   * USAGE : countAll('users',"WHERE `id`='23'");
   * */
  function countAll($table_name='', $where='')
  {

    $query = "SELECT COUNT(*) as `total` FROM `$table_name` $where";
    pr($query);
    $result = mysql_query($query) or die(mysql_error());
    $ans = mysql_fetch_assoc($result);
    return $ans['total'];
  }


  function showStatus($status, $url='', $id=0,$xtra='')
  {
    return ($status==0)?
    '<a href="'.$url.'?id='.$id.'&status=0'.$xtra.'">InActive</a>':
    '<a href="'.$url.'?id='.$id.'&status=1'.$xtra.'">Active</a>';
  }

  function error($msg='')
  {
    return '<span style="border:1px solid red;background-color:pink;padding:10px;color:red;font-size:20px" >'.$msg.'</span>';
  }


  function success($msg='')
  {
    return '<span style="border:1px solid green;background-color:lightgreen;padding:10px;color:green;font-size:20px" >'.$msg.'</span>';
  }



  function avatar_upload($data,$current_avatar='')
  {
    $_FILES = $data;
    $fileSize = 1; // 1 MB
    //echo 1024*512;exit;
    $file_name = date('ymdHis').'_'.$_FILES['avatar']['name'];

    $source = $_FILES['avatar']['tmp_name'];
    $dest = "uploads/$file_name";

    pr($_FILES);

    // copy($source, $dest);

    if($_FILES['avatar']['error'] == 0) {

      if($_FILES['avatar']['size'] < 1024*1024*$fileSize){
        $is_moved = move_uploaded_file($source, $dest);
        if($is_moved){
          $return =  array(
          'flag'=>1,
          'msg'=>success('Success !!!'),
          'name'=>$file_name);
        } else {
          $return =   array('flag'=>0,'msg'=>error('Failure !!!'));
        }
      } else {
        $return =   array(
        'flag'=>0,
        'msg'=>error("Uploaded File size should not exceed to $fileSize MB"),
        'name'=>$file_name);
      }
    }

    /*
     *  Code to generate thumb
     */
    require_once ('thumbnail/thumb.php');
    $img -> max_x = 100;
    $img -> max_y = 100;
    $img -> GenerateThumbFile($dest, "uploads/wall/$file_name");

    $img->max_x        = 50;
    $img->max_y        = 50;
    $img->GenerateThumbFile($dest, "uploads/chats/$file_name");

    if($current_avatar != '' && $return['flag']==1){
      unlink("uploads/wall/$current_avatar");
      unlink("uploads/chats/$current_avatar");
      unlink("uploads/$current_avatar");
    }
    return $return;
  }

  function setMessage($msg)
  {
    $_SESSION['msg'] = $msg;
  }

  function getMessage()
  {
    $msg = '';
    if(isset($_SESSION['msg'])){
      $msg = $_SESSION['msg'];
      unset( $_SESSION['msg']);
    }
    return $msg;
  }
  /*
   *@param $ids STRING "1,2,3,4"
   *@param $table_name STRING
   *@return Num of deleted rows
   * */
  function deleteByIs($table_name, $ids='')
  {
    if($ids==''){
      return false;
    }
    $query = "DELETE FROM `$table_name` WHERE `id` IN($ids)";
    pr($query);
    mysql_query($query) or die(mysql_error());

    return mysql_affected_rows();
  }


